package com.auction.job.core.schedule;

import com.auction.job.domain.config.SystemConfig;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yisu.auction.ewf.common.spring.SpringContext;
import com.yisu.auction.ewf.common.web.HttpWebClient;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by nichole on 2017/8/19.
 */
public class OpenPrizeJob extends BaseJob {
    private static final int OPEN_PRIZE_SUCCESS = 0;
    protected String prizeId;

    public void setPrizeId(String prizeId) {
        this.prizeId = prizeId;
    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        SystemConfig systemConfig = SpringContext.getBean("systemConfig");
        Map<String, String> params = new HashMap<>();
        params.put("prizeId", prizeId);
        String result = HttpWebClient.post(systemConfig.getOpenPrizeUrl(), params);
        LOG.info("open prize response for prize[{}]: {}", prizeId, result);

        JsonObject jsonObject= new JsonParser().parse(result).getAsJsonObject();
        int errorCode = jsonObject.get("errorCode").getAsInt();
        if(errorCode == OPEN_PRIZE_SUCCESS) {
            LOG.info("successfully opened prize for prize[{}]", prizeId);
            QuartzManager.removePurchaseJob(prizeId);
            QuartzManager.removeOpenPrizeJob(prizeId);
            QuartzManager.removeDupBuyJob(prizeId);
            int nextPrizeId = jsonObject.get("data").getAsInt();
            if(nextPrizeId > 0) {
                QuartzManager.addPurchaseJob(String.valueOf(nextPrizeId));
            }
        } else {
            LOG.error("failed to open prize for prize[{}], error code[{}], error message[{}]",
                    new String[]{prizeId, String.valueOf(errorCode), jsonObject.get("errorMessage").getAsString()});

            QuartzManager.removeOpenPrizeJob(prizeId);
        }
    }
}
